//
//  JSWebMethodDelegate.m
//  BaseProject
//
//  Created by 松云 on 2018/4/10.
//  Copyright © 2018年 CBFOfZerdoor. All rights reserved.
//

#import "JSWebMethodHandler.h"
#import "JSWebMethodManager.h"
#import "JSWebControllerManager.h"
#import <UIKit/UIKit.h>
#import "CImagePicker.h"
#import "JSWebController.h"
#import "JSWebCallbackManager.h"
#import "PayFactory.h"

@implementation JSWebMethodHandler


- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
        NSLog(@"%@", message);
        //服务器固定格式写法 window.webkit.messageHandlers.名字.postMessage(内容);
        [self receivedMessageName:message.name body:message.body];
}

-(void)receivedMessageName:(NSString *)name body:(id)body{
    if ([body isKindOfClass:[NSDictionary class]]) {
        if ([name isEqualToString:@"goWebpage"]) {//1、跳转到指定网页
            [JSWebControllerManager nextPageWithUrl:[body objectForKey:@"url"] type:[[body objectForKey:@"goType"] integerValue] callback:[body objectForKey:@"jsCallback"]];
            //                        [self goWebpageWith:[body objectForKey:@"url"] type:[[body objectForKey:@"goType"] integerValue] callback:[body objectForKey:@"jsCallback"] config:config];
            
        }
        else if ([name isEqualToString:@"goNativePage"]) {//2、跳转到指定的原生页面
            [self goNativePageWith:[body objectForKey:@"pageClassName"] paramStr:[body objectForKey:@"paramStr"] callback:[body objectForKey:@"jsCallback"]];
            
        }
        else if ([name isEqualToString:@"togglePush"]) {//3、切换原生推送开关
            
            //            [self.jsHandler togglePushWith:[[body objectForKey:@"togglePush"] integerValue] callback:[body objectForKey:@"jsCallback"] config:config];
            
        }
        else if ([name isEqualToString:@"callPhone"]) {//4、原生拨打电话
            
            [self callPhoneWithNumber:[body objectForKey:@"phoneNum"]];
            
        }
        else if ([name isEqualToString:@"goBack"]) {//5、原生返回页面
            JSWebController *vc = [JSWebControllerManager currentVC];
            if (vc.wkWebView.canGoBack) {
                [vc.wkWebView goBack];
                [vc reloadUrl];
            }else{
                [vc.navigationController popViewControllerAnimated:YES];
            }
//                        [self.jsHandler goBackWith:[[body objectForKey:@"index"] integerValue] callback:[body objectForKey:@"jsCallback"] config:config];
            
        }
        else if ([name isEqualToString:@"uploadSelectedImg"]) {//6、从原生选择图片上传
            
            [self uploadSelectedImgWithCallback:[body objectForKey:@"jsCallback"]];
            
        }else if ([name isEqualToString:@"toPlayVideo"]) {//6、从原生播放视频
            
            [self playVideoUrl:[body objectForKey:@"url"] name:[body objectForKey:@"name"] callback:[body objectForKey:@"jsCallback"]];
            
        }
        else if ([name isEqualToString:@"payment"]) {//7、支付
            
                        [self paymentWith:[[body objectForKey:@"payType"] integerValue] payStr:[body objectForKey:@"payStr"] callback:[body objectForKey:@"jsCallback"]];
            
        }
        else if ([name isEqualToString:@"share"]) {//8、三方分享
            
            //            [self.jsHandler shareWith:[[body objectForKey:@"shareType"] integerValue] title:[body objectForKey:@"title"] text:[body objectForKey:@"text"] url:[body objectForKey:@"url"] coverUrl:[body objectForKey:@"coverUrl"] callback:[body objectForKey:@"jsCallback"] config:config];
            
        }
        else if ([name isEqualToString:@"thirdPartyLogin"]) {//9、三方登录
            
            //            [self.jsHandler thirdPartyLoginWith:[[body objectForKey:@"loginType"] integerValue] callback:[body objectForKey:@"jsCallback"] config:config];
            
        }
        else if ([name isEqualToString:@"getUserInfo"]) {//11、获取用户信息
            
            //            [self.jsHandler getUserInfoWith:[[body objectForKey:@"userId"] integerValue] callback:[body objectForKey:@"jsCallback"] config:config];
            
        }
        else if ([name isEqualToString:@"locate"]) {//定位
            
            //            [self.jsHandler locateWith:<#(NSInteger)#> openGps:<#(BOOL)#> coortype:<#(NSString *)#> scanspan:<#(NSInteger)#> needAddr:<#(BOOL)#> callback:<#(NSString *)#> config:<#(BaseWebConfig *)#>]
            
        }
        else if ([name isEqualToString:@"openMapNavi"]) {//13、打开三方地图导航
            
            //            [self.jsHandler openMapNaviWith:[[body objectForKey:@"type"] integerValue] lng:[body objectForKey:@"lng"] lat:[body objectForKey:@"lat"] dest:[body objectForKey:@"dest"] callback:[body objectForKey:@"jsCallback"] config:config];
            
        }
        else if ([name isEqualToString:@"saveCurrPageCacheUrls"]) {//14、保存当前页里的需要缓存的Url
            
            //            [self.jsHandler saveCurrPageCacheUrlsWith:[body objectForKey:@"type"] fixUrls:[body objectForKey:@"fixUrls"] callback:[body objectForKey:@"jsCallback"] config:config];
            
        }
        else if ([name isEqualToString:@"reloadSpecialCachedUrls"]) {//15、重载指定的缓存Url
            
            
            
        }
        else if ([name isEqualToString:@"reloadDataWhenComeBack"]) {//16、返回回来需要重新加载数据的URL集合
            
            
            
        }else if ([name isEqualToString:@"newUploadSelectedImg"]) {//钜派专用，从原生上传图片
            
            //            [self.jsHandler newUploadImgWithType:nil callBack:[body objectForKey:@"jsCallback"] config:config];
        }
        
        
    }
    
    //    if ([body isKindOfClass:[NSString class]]) {
    ////        NSDictionary * dic = [OpenFunctions ObjectWithJson:body];
    ////        if ([dic[@"type"]isEqualToString:@"toHttp"]) {
    ////            [self.jsHandler goWebpageWith:dic[@"data"] config:config];
    //        }
    //        else if ([dic[@"type"]isEqualToString:@"function"]) {
    //            if ([dic[@"data"][@"msg"] isEqualToString:@"goBack"]) {
    //                [self.jsHandler gobackWithConfig:config];
    //            }
    //        }
    //    }
    
    
    if([body isKindOfClass:[NSArray class]]) {
        //        if ([name isEqualToString:@"advancedUrls"]) {
        //            NSMutableArray * temp = [NSMutableArray array];
        //            for (NSString * url in body) {
        //                if (![self.advancedWebGroups.allKeys containsObject:url]) {
        //                    [temp addObject:url];
        //                }
        //            }
        //            [config.advancedUrls addObjectsFromArray:temp];
        //            if (config.isUsed) {
        //                dispatch_async(dispatch_get_main_queue(), ^{
        //                    [self.jsHandler addAdvancedWebViewWithUrls:config.advancedUrls needLoadData:NO];
        //                });
        //            }
        //        }
    }
}

/**
 原生拨打电话
 @param phoneNum 电话号码
 */
-(void)callPhoneWithNumber:(NSString *)phoneNum {
    UIWebView * callWebview = [[UIWebView alloc]init];
    [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel:%@",phoneNum]]]];
    [[UIApplication sharedApplication].keyWindow addSubview:callWebview];
}

//原生上传图片
-(void)uploadSelectedImgWithCallback:(NSString *)callback{
    
    JSWebController * curVc = [JSWebControllerManager currentVC];
    
    
    if (curVc) {
        
        CImagePicker * imgpicker = [CImagePicker imagePicker];
        [imgpicker openGallery:^(UIAlertController *alertController) {
            [curVc presentViewController:alertController animated:YES completion:nil];
        } didChoose:^{
            [curVc presentViewController:imgpicker.imagePickerController animated:YES completion:nil];
        } didFinish:^(UIImage *img) {
            
            if (img) {
                //上传图片到服务器
                NSArray *imgArray = @[img];
                NSLog(@"选取照片成功%@",imgArray);
                NSString *returnJSStr = [NSString stringWithFormat:@"%@(0,'%@','%@')",callback,@"testUrl",@"noPrefixPath"];
                [JSWebCallbackManager callBackStr:returnJSStr backSuccessBlock:^(id  _Nullable result) {
                    
                }];
                //                [curVc.webView evaluateJavaScript:returnJSStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {
                //                    //
                //                    if (!error) {
                //                        NSLog(@"回调成功");
                //                    }
                //                }];
                
                
                //
                //                [BaseRequestManager request_uploadImagesWithImages:imgArray type:11 Success:^(NSDictionary *resultDic) {
                //
                //                    NSString *imgURL = resultDic[@"path"];
                //                    NSString *noPrefixPath = resultDic[@"noPrefixPath"];
                //                    NSString *returnJSStr = [NSString stringWithFormat:@"%@(0,'%@','%@')",callback,imgURL,noPrefixPath];
                //
                //                    [curVc.wkWebView evaluateJavaScript:returnJSStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {
                //
                //                        if (!error) {
                //                            //回调H5 成功
                //                        }
                //                    }];
                
                //                } Failure:^(NSString *msg, NSDictionary *resultDic) {
                //                    [NSString showTemporaryMessage:msg];
                //                }];
                
            }else {
                NSLog(@"选取照片失败");
            }
            
        } didCancel:^{
            NSLog(@"qqqqq选取照片取消");
        }];
        
    }else {
        NSLog(@"can't find currrent WebController");
    }
}

-(void)playVideoUrl:(NSString *)url name:(NSString *)name callback:(NSString *)callback{
    NSLog(@"播放视频 %@ %@ %@",url,name,callback);
}

-(void)goNativePageWith:(NSString *)pageClassName paramStr:(NSString *)paramStr callback:(NSString *)callback{
    JSWebController * curVc = [JSWebControllerManager currentVC];
    if (curVc) {
        Class class = NSClassFromString(pageClassName);
        if (!class) {//对应类没找到
            NSLog(@"no class equal to [%@]",pageClassName);
            return;
        }
        
        UIViewController * targetVc;
        id obj = [[class alloc]init];
        targetVc = obj;
        if (paramStr && paramStr.length > 0) {
            
            SEL selector = NSSelectorFromString(@"initWithParamStr:");
            IMP imp = [targetVc methodForSelector:selector];
            void (*func)(id, SEL, NSString *) = (void *)imp;
            func(targetVc, selector, paramStr);
            
        }
        targetVc.title = @"空白原生页面";
        [curVc setHidesBottomBarWhenPushed:YES];
        [curVc.navigationController pushViewController:targetVc animated:YES];
    }else {
        NSLog(@"can't find currrent WebController");
    }
}

-(void)paymentWith:(NSInteger)type payStr:(id)body callback:(NSString *)callback{
    [PayFactory share].type = type;
    [PayFactory payOrder:body succeed:^(NSString *str) {
        
    } fail:^(NSString *failStr) {
        
    }];
//    if (type == 0) {
//        [[PayWx share] payOrder:body succeed:^(NSString *str) {
//
//        } fail:^(NSString *failStr) {
//            NSString *returnJSStr = [NSString stringWithFormat:@"%@(0,'%@')",callback,failStr];
//            [JSWebCallbackManager callBackStr:returnJSStr backSuccessBlock:^(id  _Nullable result) {
//
//            }];
//        }];
//    }else{
//        [[PayAli share] payOrder:body succeed:^(NSString *str) {
//
//        } fail:^(NSString *failStr) {
//            [JSWebCallbackManager callBackStr:@"payment('1','1','1')" backSuccessBlock:^(id  _Nullable result) {
//
//            }];
//            NSString *returnJSStr = [NSString stringWithFormat:@"%@(0,'%@')",callback,failStr];
//            [JSWebCallbackManager callBackStr:returnJSStr backSuccessBlock:^(id  _Nullable result) {
//
//            }];
//        }];
//    }
}

-(void)dealloc{
    NSLog(@"事件处理器被销毁");
}
@end
